﻿// 应用场景
var mySwiper = new Swiper('.swiper-container', {
    loop: false,
    slidesPerView: 'auto',
    slidesPerView: 3,
    loopedSlides: 3,
    navigation: {
        nextEl: '.swiper-button-next',
        prevEl: '.swiper-button-prev',
    },
})
// 服务应用
var mySwiper = new Swiper('.swiper-container1', {
    loop: false,
    // autoplay: true,
    // delay: 5000,
    // effect : 'coverflow',
    // centeredSlides: true,
    spaceBetween: 50,
    slidesPerView: 'auto',
    slidesPerView: 2,
    loopedSlides: 2,
    navigation: {
        nextEl: '.swiper-button-next',
        prevEl: '.swiper-button-prev',
    },
})

function abilityExperience() {
    let nlty = $("#nlty").offset()
    $('body,html').animate({
        scrollTop: nlty.top
    }, 200);
}

// 能力体验录音动画
var params = {
    container: document.getElementById('nlty_sbanimate'),
    renderer: 'svg',
    loop: true,
    autoplay: true,
    animationData: animationData
};
var anim;
// anim = lottie.loadAnimation(params);
var sessionId;
//录音
var recorder;
var ws, config = {};
var time = 0, timeStr = '', timer;

var isopen = false;


function initWs() {
    sessionId = "ASTDEMO_" + _getRandomString(8);
    //var wsuri = "wss://50.78.128.152:33678" + "/tuling/ast/v2/" + sessionId + "?appId=10101&bizId=123&bizName=AST_DEMO";
    //var wsuri = "ws://50.78.128.152:8585"  + "/tuling/ast/v2/" + sessionId + "?appId=10101&bizId=123&bizName=AST_DEMO";
    var host = "172.16.11.211:10001";
    var path = "/realtimeTranscribe/" + sessionId;
    var apiKey = "1qaz2wsx";
    var apiSecret = "C68D62C5E68843F7AAD29F864B9C042";
    var requestUrl = assembleRequestUrl(host, path, apiKey, apiSecret);
    console.log(requestUrl);
    ws = new WebSocket(requestUrl);
    ws.onopen = function () {
    };
    ws.onmessage = function (e) {
        var jsonResponse = JSON.parse(e.data);
        console.log(e.data);
        __show2(jsonResponse);
    };
    ws.onclose = function (e) {
        if (e.code === 1001) {
            stop();
        }
    };
    config.ws = ws;
};

function assembleRequestUrl(host, path, apiKey, apiSecret) {
    var url = "ws://" + host + path;
    var date = new Date().toGMTString();
    var algorithm = 'hmac-sha256';
    var headers = 'host date request-line';
    var signatureOrigin = `host: ${host}\ndate: ${date}\nGET ${path} HTTP/1.1`;
    var signatureSha = CryptoJS.HmacSHA256(signatureOrigin, apiSecret);
    var signature = CryptoJS.enc.Base64.stringify(signatureSha);
    var authorizationOrigin = `api_key="${apiKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`;
    var authorization = btoa(authorizationOrigin);
    url = `${url}?authorization=${authorization}&date=${date}&host=${host}`;
    return url;
}


function __show2(e, data) {
    var text = "";
    if (e.ws != null) {
        for (var i = 0; i < e.ws.length; i++) {
            var cw = e.ws[i].cw;
            if (cw != null) {
                text = text + cw[0].w + " ";
            }
        }

    }

    $(".ast-temp").remove();
    if (e.msgtype == "sentence") {
        $("#showText").append(text);
    } else {
        $("#showText").append("<temp class='ast-temp'>" + text + "</temp>");
    }


}

//获取长度为len的随机字符串
function _getRandomString(len) {
    len = len || 32;
    var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; // 默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1
    var maxPos = $chars.length;
    var uid = '';
    for (i = 0; i < len; i++) {
        uid += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return uid;
}


function startInit() {

    isopen = true;

    time = 0;
    timeStr = "00:00";
    timer = setInterval(function () {
        time += 1;
        var last__ = time % 3600;
        var m = (parseInt(last__ / 60) < 10) ? ('0' + parseInt(last__ / 60)) : parseInt(last__ / 60);
        var s = (time % 60 < 10) ? ('0' + parseInt(time % 60)) : parseInt(time % 60);
        timeStr = '' + m + ':' + s;
        $('#nlty_sbtime').html(timeStr);
    }, 1000)

    initWs();
    HZRecorder.get(function (rec) {
        recorder = rec
        recorder.start()
    }, config)
}

function stopInit() {

    timeStr = ''
    clearInterval(timer)
    $('#nlty_sbtime').html(timeStr);

    recorder.stop();
    ws.close();
    sessionId = null;
    isopen = false;

    $("#showText").html("");

}


function startRecording() {
    let nltyMkf = $('#nlty_ht').is(":visible")
    if (nltyMkf) {
        startInit();

        $('#nlty_ht').hide()
        $('#nlty_sb').show()

        $('.nlty_start').text('结束识别')
        anim = lottie.loadAnimation(params);

        setTimeout(() => {
            lottie.loadAnimation(params).destroy();
            $('#nlty_ht').show()
            $('#nlty_sb').hide()
            stopInit();

            $('.nlty_start').text('开始识别')
        }, 60000)
    } else {
        lottie.loadAnimation(params).destroy();
        $('#nlty_ht').show()
        $('#nlty_sb').hide()

        stopInit();


        $('.nlty_start').text('开始识别')
    }
}